#!/usr/bin/env python
import sys, urllib2

# http://www.crummy.com/software/BeautifulSoup/download/BeautifulSoup.py
# http://www.crummy.com/software/BeautifulSoup/documentation.html
from BeautifulSoup import BeautifulSoup

if len(sys.argv) != 2:
    print 'Usage: %s <tip number>' % sys.argv[0]
    sys.exit()

tip_number = int(sys.argv[1])
tip_url = 'http://www.vim.org/tips/tip.php?tip_id=%d' % tip_number
tip_doc = urllib2.urlopen(tip_url)
soup = BeautifulSoup(tip_doc)

if soup.find(text='Vim Online Error'):
    print soup.find('p', 'errorheader').nextSibling.nextSibling.renderContents()
    sys.exit(1)

created     = soup.find(text='created:') \
                .parent.parent.findAll('td')[2].renderContents().strip()
complexity  = soup.find(text='complexity:') \
                .parent.parent.findAll('td')[6].renderContents().strip()
author      = soup.find(text='author:') \
                .parent.parent.findAll('td')[2].renderContents().strip()
version     = soup.find(text='as of Vim:') \
                .parent.parent.findAll('td')[6].renderContents().strip()
body        = soup.find('code').renderContents()


# http://code.google.com/p/support/wiki/WikiSyntax
# Print the actual tip
print '''
= Tip #%(tip_number)d =

|| Author || %(author)s ||
|| Created On || %(created)s ||
|| Complexity || %(complexity)s ||
|| Version of Vim required || %(version)s ||

%(body)s


''' % locals()

print '''

== Additional Notes ==

'''

notes_table = soup.find('h1', text='Additional Notes').parent.nextSibling.nextSibling
list_items  = notes_table.findAll('tr')[:-1] # Ignore the 'add note' tip

note_number = 1
for row_number in range(0, len(list_items), 2):
    metadata = list_items[row_number]

    author_string = metadata.td.renderContents().strip()
    date_position = author_string.find("<font")
    assert date_position != -1
    author_string = author_string[:date_position]
    note_author = author_string.strip()[:-1]

    note_date = metadata.td.font.renderContents().strip()
    content  = list_items[row_number+1]
    note_body = content.td.tt.renderContents().strip()

    # Print the tip notes (i.e. additional comments)
    print '''
=== Note %(note_number)d ===

|| By || %(note_author)s ||
|| On || %(note_date)s ||

%(note_body)s

''' % locals()

    note_number += 1


# vim: tabstop=4 shiftwidth=4 expandtab backspace=indent autoindent smartindent
# The End
